﻿using BakaGit.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BakaGit
{
    public partial class ConfigForm : BaseForm
    {
        public ConfigForm()
        {
            InitializeComponent();
        }

        private void ConfigForm_Load(object sender, EventArgs e)
        {

        }

        private bool verifyInput()
        {
            txtProjectUrl.WithError = false;
            txtUn.WithError = false;
            txtPw.WithError = false;
            if (!txtProjectUrl.Text.StartsWith("https://") && !txtProjectUrl.Text.StartsWith("http://"))
            {
                txtProjectUrl.WithError = true;
                MetroFramework.MetroMessageBox.Show(this, "请输入正确的项目地址", " ");
                fixWindowTop();
                return false;
            }
            if (!System.Text.RegularExpressions.Regex.IsMatch(txtEmail.Text, "^.*@.*$"))
            {
                txtEmail.WithError = true;
                MetroFramework.MetroMessageBox.Show(this, "请输入正确的电子邮箱", " ");
                fixWindowTop();
                return false;
            }
            if (txtUn.Text.Length < 1)
            {
                txtUn.WithError = true;
                MetroFramework.MetroMessageBox.Show(this, "请输入用户名", " ");
                fixWindowTop();
                return false;
            }


            if (txtPw.Text.Length < 6)
            {
                txtPw.WithError = true;
                MetroFramework.MetroMessageBox.Show(this, "请输入密码", " ");
                fixWindowTop();
                return false;
            }

            return true;
        }

        private void metroButton1_Click(object sender, EventArgs e)
        {
            if (!verifyInput())
            {
                return;
            }
            
            String projectUrl = txtProjectUrl.Text;
            String projectName = projectUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Last();
            if (projectName.EndsWith(".git")) { projectName = projectName.Substring(0, projectName.Length - 4); }


            String projectPath = projectName;
            GitProject gp = new GitProject(projectName, projectUrl, projectPath, txtUn.Text, txtPw.Text, txtEmail.Text);
            if (Directory.Exists(Path.Combine(Environment.CurrentDirectory, projectName, ".git")))
            {
                Program.info = gp;
                Close();
                return;
            }




            this.Enabled = false;
            try
            {
                CloneProject(gp);

                MetroFramework.MetroMessageBox.Show(this, "项目初始化完成！", "");
                this.Enabled = true;
                Program.info = gp;
                Close();
            }
            catch(Exception ex)
            {
                this.Enabled = true;
                MetroFramework.MetroMessageBox.Show(this, "项目初始化失败：\r\n"+ex.Message, "错误");
                fixWindowTop();
                metroButton1.Text = "开始";
            }
            metroButton1.Text = "正在准备项目";
            metroButton1.FontSize = MetroFramework.MetroButtonSize.Small;
        }

        public static void CloneProject(GitProject project)
        {
            LibGit2Sharp.CloneOptions option = new LibGit2Sharp.CloneOptions();
            option.FetchOptions.CertificateCheck = (cert, isvalid, host) => true;

            option.FetchOptions.CredentialsProvider = (string1, string2, suppertCridentials) =>
            {
                return new LibGit2Sharp.UsernamePasswordCredentials() { Username = project.username, Password = project.GetPasswordDecrypted() };
            };

            option.FetchOptions.OnProgress = (progress) =>
            {
                Console.WriteLine(progress);
                return true;
            };

            LibGit2Sharp.Repository.Clone(project.repoUrl, Path.Combine(Environment.CurrentDirectory, project.localPath), option);
        }

        private void btnCreateConfigOnly_Click(object sender, EventArgs e)
        {
            if (!verifyInput())
            {
                return;
            }

            String projectUrl = txtProjectUrl.Text;
            String projectName = projectUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Last();
            if (projectName.EndsWith(".git")) { projectName = projectName.Substring(0, projectName.Length - 4); }
            String projectPath = projectName;
            GitProject gp = new GitProject(projectName, projectUrl, projectPath, txtUn.Text, txtPw.Text, txtEmail.Text);


            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "BakaGit 仓库配置文件|*.bakarepo";
            dlg.Title = "请将配置文件放在想要放仓库文件夹的地方";
            dlg.FileName = projectName + ".bakarepo";
            if(dlg.ShowDialog(this) == DialogResult.OK)
            {
                File.WriteAllText(dlg.FileName,JsonConvert.SerializeObject(gp));
                MetroFramework.MetroMessageBox.Show(this, "配置文件保存完成。\r\n可以将.bakarepo的打开方式设置为BakaGit，并用BakaGit打开.bakarepo文件");
                fixWindowTop();
                Close();
            }

        }

        private void btnRegisterFileType_Click(object sender, EventArgs e)
        {
            if (MetroFramework.MetroMessageBox.Show(this, "是否注册BAKAREPO的打开方式？", "打开方式", MessageBoxButtons.YesNo) == DialogResult.Yes) {
                RegisterFileTypeHelper.RegisterOrUpdate();
                MetroFramework.MetroMessageBox.Show(this, "文件类型注册完成。");
                fixWindowTop();
            }
        }
    }
}
